<!--
  角色管理页面 - 系统角色管理功能
  支持dialog模式和tabs模式两种显示方式
-->
<template>
  <div class="container">
    <!-- tabs模式 -->
    <div v-if="displayMode === 'tabs'" class="tabs-container">
      <!-- 标签页头部 -->
      <div class="tabs-header-container">
        <!-- 左滚动按钮 -->
        <div class="scroll-button scroll-left" @click="scrollTabs('left')" v-show="tabsList.length > 3">
          <el-icon><ArrowLeft /></el-icon>
        </div>
        
        <!-- 标签页头部 -->
        <div class="tabs-header" ref="tabsHeaderRef">
          <div class="tab-items-wrapper">
            <div 
              v-for="(tab, index) in tabsList" 
              :key="tab.id"
              class="tab-item"
              :class="{ 'tab-active': activeTabId === tab.id, 'tab-unclosable': index === 0 }"
              @click="handleTabClick(tab)"
              :ref="el => { if (activeTabId === tab.id) activeTabRef = el }"
            >
              <span class="tab-title">{{ tab.title }}</span>
              <!-- 第一个tab不显示关闭按钮，其他tab显示 -->
              <div 
                v-if="index > 0" 
                class="tab-close"
                @click.stop="handleTabClose(tab)"
              >
                <el-icon><Close /></el-icon>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 右滚动按钮 -->
        <div class="scroll-button scroll-right" @click="scrollTabs('right')" v-show="tabsList.length > 3">
          <el-icon><ArrowRight /></el-icon>
        </div>
      </div>
      
      <!-- 标签页内容区域 -->
      <div class="tabs-content">
        <div 
          v-for="tab in tabsList" 
          :key="tab.id"
          class="tab-pane"
          :class="{ 'tab-pane-active': activeTabId === tab.id }"
        >
          <!-- 动态组件渲染 -->
          <component 
            v-if="activeTabId === tab.id"
            :is="getTabComponent(tab.component)"
            v-bind="getTabProps(tab)"
            v-on="getTabEvents(tab)"
          />
        </div>
      </div>
    </div>
    
    <!-- dialog模式 -->
    <div v-else class="dialog-container">
      <!-- 角色列表 -->
      <RoleList display-mode="dialog" :role-data="roleData" :loading="loading"
        @add-role="handleAddRole" @edit-role="handleEditRole" @toggle-status="handleToggleStatus" 
        @delete-role="handleDeleteRole" @refresh="handleRefresh" @search="handleSearch" 
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />

      <!-- 角色表单弹窗 -->
      <RoleForm :display-mode="'dialog'" :mode="formMode"
        :role-id="selectedRoleId" :visible="formVisible" :role-data="selectedRoleData"
        @update:visible="formVisible = $event" @success="handleFormSuccess" @close="handleFormClose" />
    </div>
  </div>
</template>

<script setup>
import { 
  ref, 
  reactive, 
  computed, 
  watch, 
  onBeforeMount,
  onMounted, 
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  onErrorCaptured,
  nextTick 
} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { Close, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import RoleForm from '@/components/system/role/RoleForm.vue'
import RoleList from '@/components/system/role/RoleList.vue'

// 组件名称
defineOptions({
  name: 'SystemRoleIndex'
}) 
// 路由
const route = useRoute()

// 响应式变量声明（按照模板中的顺序）
const loading = ref(false)
const formVisible = ref(false)
const formMode = ref('add')
const selectedRoleId = ref(null)
const selectedRoleData = ref({})
const activeTabId = ref('role-list')
const tabsHeaderRef = ref(null) // 标签页头部容器引用
const activeTabRef = ref(null) // 当前激活标签页引用

// 响应式对象
const tabsList = reactive([
  {
    id: 'role-list',
    title: '角色列表',
    type: 'list',
    component: 'RoleList',
    closable: false // 第一个标签页不可关闭
  }
])

// 角色数据和分页信息
const roleList = reactive([
  {
    id: 1,
    roleName: '超级管理员',
    roleCode: 'SUPER_ADMIN',
    description: '系统超级管理员，拥有所有权限',
    status: 1,
    createTime: '2024-01-01 10:00:00',
    updateTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    roleName: '系统管理员',
    roleCode: 'ADMIN',
    description: '系统管理员，拥有大部分管理权限',
    status: 1,
    createTime: '2024-01-02 10:00:00',
    updateTime: '2024-01-02 10:00:00'
  },
  {
    id: 3,
    roleName: '普通用户',
    roleCode: 'USER',
    description: '普通用户，基础查看权限',
    status: 0,
    createTime: '2024-01-03 10:00:00',
    updateTime: '2024-01-03 10:00:00'
  },
  {
    id: 4,
    roleName: '内容管理员',
    roleCode: 'CONTENT_ADMIN',
    description: '内容管理员，负责内容审核和管理',
    status: 1,
    createTime: '2024-01-04 10:00:00',
    updateTime: '2024-01-04 10:00:00'
  },
  {
    id: 5,
    roleName: '数据分析师',
    roleCode: 'DATA_ANALYST',
    description: '数据分析师，负责数据统计和分析',
    status: 1,
    createTime: '2024-01-05 10:00:00',
    updateTime: '2024-01-05 10:00:00'
  },
  {
    id: 6,
    roleName: '客服专员',
    roleCode: 'CUSTOMER_SERVICE',
    description: '客服专员，处理用户咨询和问题',
    status: 1,
    createTime: '2024-01-06 10:00:00',
    updateTime: '2024-01-06 10:00:00'
  },
  {
    id: 7,
    roleName: '运营专员',
    roleCode: 'OPERATION_SPECIALIST',
    description: '运营专员，负责活动策划和执行',
    status: 1,
    createTime: '2024-01-07 10:00:00',
    updateTime: '2024-01-07 10:00:00'
  },
  {
    id: 8,
    roleName: '市场推广',
    roleCode: 'MARKETING',
    description: '市场推广，负责品牌推广和宣传',
    status: 1,
    createTime: '2024-01-08 10:00:00',
    updateTime: '2024-01-08 10:00:00'
  },
  {
    id: 9,
    roleName: '产品经理',
    roleCode: 'PRODUCT_MANAGER',
    description: '产品经理，负责产品规划和设计',
    status: 1,
    createTime: '2024-01-09 10:00:00',
    updateTime: '2024-01-09 10:00:00'
  },
  {
    id: 10,
    roleName: 'UI设计师',
    roleCode: 'UI_DESIGNER',
    description: 'UI设计师，负责界面设计和美化',
    status: 1,
    createTime: '2024-01-10 10:00:00',
    updateTime: '2024-01-10 10:00:00'
  },
  {
    id: 11,
    roleName: '前端工程师',
    roleCode: 'FRONTEND_DEVELOPER',
    description: '前端工程师，负责前端开发工作',
    status: 1,
    createTime: '2024-01-11 10:00:00',
    updateTime: '2024-01-11 10:00:00'
  },
  {
    id: 12,
    roleName: '后端工程师',
    roleCode: 'BACKEND_DEVELOPER',
    description: '后端工程师，负责服务器端开发',
    status: 1,
    createTime: '2024-01-12 10:00:00',
    updateTime: '2024-01-12 10:00:00'
  },
  {
    id: 13,
    roleName: '测试工程师',
    roleCode: 'QA_ENGINEER',
    description: '测试工程师，负责质量保证和测试',
    status: 1,
    createTime: '2024-01-13 10:00:00',
    updateTime: '2024-01-13 10:00:00'
  },
  {
    id: 14,
    roleName: '运维工程师',
    roleCode: 'DEVOPS_ENGINEER',
    description: '运维工程师，负责系统部署和维护',
    status: 1,
    createTime: '2024-01-14 10:00:00',
    updateTime: '2024-01-14 10:00:00'
  },
  {
    id: 15,
    roleName: '安全工程师',
    roleCode: 'SECURITY_ENGINEER',
    description: '安全工程师，负责系统安全和防护',
    status: 1,
    createTime: '2024-01-15 10:00:00',
    updateTime: '2024-01-15 10:00:00'
  },
  {
    id: 16,
    roleName: '项目经理',
    roleCode: 'PROJECT_MANAGER',
    description: '项目经理，负责项目管理和协调',
    status: 1,
    createTime: '2024-01-16 10:00:00',
    updateTime: '2024-01-16 10:00:00'
  }
])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 55
})

// 角色数据（提供给RoleList组件）
const roleData = reactive({
  list: roleList,
  pagination: pagination
})

// 计算属性
const displayMode = computed(() => {
  // 根据路由meta中的type属性判断显示模式
  // type: 1 = dialog模式，type: 0 或不存在 = tabs模式
  const routeType = route.meta?.type
  return routeType === 1 ? 'tabs' : 'tabs'
})

// 响应函数声明（按照模板中的顺序）
/**
 * 标签页点击处理
 */
const handleTabClick = (tab) => {
  if (activeTabId.value !== tab.id) {
    activeTabId.value = tab.id
    // 暂时注释掉消息提示，测试切换性能
    // ElMessage.success(`切换到${tab.title}`)
  }
  
  // 自动滚动到当前激活的标签页
  nextTick(() => {
    scrollToActiveTab()
  })
}

/**
 * 滚动到当前激活的标签页
 */
const scrollToActiveTab = () => {
  if (!tabsHeaderRef.value || !activeTabRef.value) return
  
  const headerContainer = tabsHeaderRef.value
  const activeTab = activeTabRef.value
  
  // 计算滚动位置
  const headerWidth = headerContainer.offsetWidth
  const tabLeft = activeTab.offsetLeft
  const tabWidth = activeTab.offsetWidth
  const currentScrollLeft = headerContainer.scrollLeft
  
  // 判断标签页是否在可视区域内
  if (tabLeft < currentScrollLeft) {
    // 标签页在左侧不可见区域
    headerContainer.scrollLeft = tabLeft - 20
  } else if (tabLeft + tabWidth > currentScrollLeft + headerWidth) {
    // 标签页在右侧不可见区域
    headerContainer.scrollLeft = tabLeft + tabWidth - headerWidth + 20
  }
}

/**
 * 手动滚动标签页
 */
const scrollTabs = (direction) => {
  if (!tabsHeaderRef.value) return
  
  const headerContainer = tabsHeaderRef.value
  const scrollAmount = 200 // 每次滚动的像素
  
  if (direction === 'left') {
    headerContainer.scrollLeft = Math.max(0, headerContainer.scrollLeft - scrollAmount)
  } else {
    const maxScrollLeft = headerContainer.scrollWidth - headerContainer.offsetWidth
    headerContainer.scrollLeft = Math.min(maxScrollLeft, headerContainer.scrollLeft + scrollAmount)
  }
}

/**
 * 标签页关闭处理
 */
const handleTabClose = (tab) => {
  if (tab.id === activeTabId.value) {
    // 如果关闭的是当前激活的tab，需要激活其他tab
    const currentIndex = tabsList.findIndex(t => t.id === tab.id)
    if (tabsList.length > 1) {
      // 激活前一个tab，如果没有则激活后一个
      if (currentIndex > 0) {
        activeTabId.value = tabsList[currentIndex - 1].id
      } else {
        activeTabId.value = tabsList[currentIndex + 1].id
      }
    }
  }
  
  // 移除标签页
  const index = tabsList.findIndex(t => t.id === tab.id)
  if (index > -1) {
    tabsList.splice(index, 1)
    ElMessage.success(`已关闭${tab.title}`)
  }
}

/**
 * 处理搜索
 */
const handleSearch = (keyword) => {
  console.log('搜索关键词:', keyword)
  ElMessage.info('搜索功能开发中...')
}

/**
 * 处理新增角色
 */
const handleAddRole = () => {
  formMode.value = 'add'
  selectedRoleId.value = null
  selectedRoleData.value = {}
  
  if (displayMode.value === 'tabs') {
    // tabs模式：新增一个表单标签页
    const newTab = {
      id: `form-${Date.now()}`,
      title: '新增角色',
      component: 'RoleForm',
      mode: 'add',
      roleId: null,
      roleData: {},
      closable: true
    }
    tabsList.push(newTab)
    activeTabId.value = newTab.id
  } else {
    // dialog模式：显示表单弹窗
    formVisible.value = true
  }
}

/**
 * 处理编辑角色
 */
const handleEditRole = (row) => {
  formMode.value = 'edit'
  selectedRoleId.value = row.id
  selectedRoleData.value = { ...row }
  
  if (displayMode.value === 'tabs') {
    // tabs模式：新增一个表单标签页
    const newTab = {
      id: `form-${Date.now()}`,
      title: `编辑角色 - ${row.roleName}`,
      component: 'RoleForm',
      mode: 'edit',
      roleId: row.id,
      roleData: { ...row },
      closable: true
    }
    tabsList.push(newTab)
    activeTabId.value = newTab.id
  } else {
    // dialog模式：显示表单弹窗
    formVisible.value = true
  }
}

/**
 * 处理状态切换
 */
const handleToggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'

  ElMessageBox.confirm(`确定要${statusText}角色"${row.roleName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    row.status = newStatus
    row.updateTime = new Date().toLocaleString('zh-CN')
    ElMessage.success(`${statusText}成功`)
  }).catch(() => {
    // 用户取消操作，恢复原状态
    row.status = row.status === 1 ? 1 : 0
  })
}

/**
 * 处理删除角色
 */
const handleDeleteRole = (row) => {
  ElMessageBox.confirm(`确定要删除角色"${row.roleName}"吗？删除后不可恢复！`, '警告', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'error'
  }).then(() => {
    const index = roleList.findIndex(item => item.id === row.id)
    if (index > -1) {
      roleList.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

/**
 * 处理刷新
 */
const handleRefresh = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('刷新成功')
  }, 800)
}

/**
 * 处理分页大小变更
 */
const handleSizeChange = (size) => {
  pagination.pageSize = size
}

/**
 * 处理当前页变更
 */
const handleCurrentChange = (page) => {
  pagination.current = page
}

/**
 * 处理表单成功
 */
const handleFormSuccess = (result) => {
  if (result.mode === 'add') {
    // 新增成功后添加到列表
    const newRole = {
      id: Date.now(), // 临时ID，实际应从后端获取
      ...result.data,
      createTime: new Date().toLocaleString('zh-CN'),
      updateTime: new Date().toLocaleString('zh-CN')
    }
    roleList.unshift(newRole)
    pagination.total++
    ElMessage.success('角色新增成功')
  } else {
    // 编辑成功后更新列表
    const index = roleList.findIndex(item => item.id === result.data.id)
    if (index > -1) {
      roleList[index] = {
        ...roleList[index],
        ...result.data,
        updateTime: new Date().toLocaleString('zh-CN')
      }
    }
    ElMessage.success('角色更新成功')
  }
  
  // 重置表单状态
  handleFormClose()
}

/**
 * 处理表单关闭
 */
const handleFormClose = () => {
  formVisible.value = false
  formMode.value = 'add'
  selectedRoleId.value = null
  selectedRoleData.value = {}
}

/**
 * 处理表单取消（tabs模式专用）
 */
const handleFormCancel = () => {
  if (displayMode.value === 'tabs') {
    // tabs模式：关闭当前表单标签页
    const currentTab = tabsList.find(tab => tab.id === activeTabId.value)
    if (currentTab && currentTab.component === 'RoleForm') {
      handleTabClose(currentTab)
    }
  } else {
    // dialog模式：关闭弹窗
    handleFormClose()
  }
}

/**
 * 处理查看角色用户
 */
const handleViewRoleUsers = (row) => {
  if (displayMode.value === 'tabs') {
    // tabs模式：新增用户列表标签页
    const newTab = {
      id: `users-${Date.now()}`,
      title: `${row.roleName} - 用户列表`,
      component: 'RoleUsers',
      roleId: row.id,
      roleName: row.roleName,
      closable: true
    }
    tabsList.push(newTab)
    activeTabId.value = newTab.id
  } else {
    // dialog模式：显示弹窗或跳转
    ElMessage.info('查看角色用户功能开发中...')
  }
}

/**
 * 处理查看角色权限
 */
const handleViewRolePermissions = (row) => {
  if (displayMode.value === 'tabs') {
    // tabs模式：新增权限管理标签页
    const newTab = {
      id: `permissions-${Date.now()}`,
      title: `${row.roleName} - 权限管理`,
      component: 'RolePermissions',
      roleId: row.id,
      roleName: row.roleName,
      closable: true
    }
    tabsList.push(newTab)
    activeTabId.value = newTab.id
  } else {
    // dialog模式：显示弹窗或跳转
    ElMessage.info('查看角色权限功能开发中...')
  }
}

// 样式函数声明
/**
 * 初始化页面数据
 */
const initPageData = () => {
  console.log('角色管理页面数据初始化')
}

/**
 * 验证角色数据
 */
const validateRoleData = () => {
  return roleList.length > 0
}

/**
 * 获取当前激活标签页
 */
const getCurrentTab = () => {
  return tabsList.find(tab => tab.id === activeTabId.value)
}

/**
 * 获取标签页组件
 */
const getTabComponent = (componentName) => {
  const componentMap = {
    'RoleList': RoleList,
    'RoleForm': RoleForm,
    'RoleUsers': RoleList, // 临时使用RoleList，实际应该是用户列表组件
    'RolePermissions': RoleForm, // 临时使用RoleForm，实际应该是权限管理组件
  }
  return componentMap[componentName] || RoleList
}

/**
 * 获取标签页属性
 */
const getTabProps = (tab) => {
  const propsMap = {
    'RoleList': {
      'display-mode': 'tabs',
      'role-data': roleData,
      'loading': loading
    },
    'RoleForm': {
      'display-mode': 'tabs',
      'mode': tab.mode || 'add',
      'role-id': tab.roleId || null,
      'visible': true,
      'role-data': tab.roleData || {}
    },
    'RoleUsers': {
      'role-id': tab.roleId,
      'loading': loading
    },
    'RolePermissions': {
      'role-id': tab.roleId,
      'loading': loading
    }
  }
  return propsMap[tab.component] || {}
}

/**
 * 获取标签页事件
 */
const getTabEvents = (tab) => {
  const eventsMap = {
    'RoleList': {
      'add-role': handleAddRole,
      'edit-role': handleEditRole,
      'toggle-status': handleToggleStatus,
      'delete-role': handleDeleteRole,
      'refresh': handleRefresh,
      'search': handleSearch,
      'size-change': handleSizeChange,
      'current-change': handleCurrentChange,
      'view-users': handleViewRoleUsers,
      'view-permissions': handleViewRolePermissions
    },
    'RoleForm': {
      'success': handleFormSuccess,
      'cancel': handleFormCancel
    },
    'RoleUsers': {
      'refresh': handleRefresh,
      'back-to-list': () => handleTabSwitch('role-list')
    },
    'RolePermissions': {
      'save': handleFormSuccess,
      'back-to-list': () => handleTabSwitch('role-list')
    }
  }
  return eventsMap[tab.component] || {}
}

/**
 * 处理标签页切换
 */
const handleTabSwitch = (tabId) => {
  activeTabId.value = tabId
}

// 生命周期钩子
onBeforeMount(() => {
  // 组件挂载前执行的逻辑
  console.log('角色管理页面即将挂载')
})

onMounted(() => {
  // 组件挂载后执行的逻辑
  initPageData()
  console.log('角色管理页面已加载')
})

onBeforeUpdate(() => {
  // 组件更新之前执行的逻辑
  nextTick(() => {
    // 在DOM更新之后执行的逻辑
  })
})

onUpdated(() => {
  // 组件更新之后执行的逻辑
})

onBeforeUnmount(() => {
  // 组件卸载前执行的逻辑
  console.log('角色管理页面即将卸载')
})

onUnmounted(() => {
  // 组件卸载后执行的逻辑
})

onErrorCaptured((err, instance, info) => {
  // 捕获来自后代组件的错误
  console.error('角色管理页面错误:', err, info)
  return false // 阻止错误继续向上传播
})
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
  
  // tabs模式样式
  .tabs-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    
    // 标签页头部容器
    .tabs-header-container {
      display: flex;
      align-items: center;
      background-color: #fff;
      border-bottom: 1px solid #e8e8e8;
      position: relative;
      
      // 滚动按钮样式
      .scroll-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 32px;
        height: 40px;
        cursor: pointer;
        background-color: #fafafa;
        border: 1px solid #e8e8e8;
        z-index: 10;
        transition: all 0.2s ease;
        
        &:hover {
          background-color: #f0f0f0;
        }
        
        &:active {
          transform: scale(0.95);
        }
        
        &.scroll-left {
          border-right: none;
          border-radius: 4px 0 0 0;
        }
        
        &.scroll-right {
          border-left: none;
          border-radius: 0 4px 0 0;
        }
      }
      
      // 标签页头部
      .tabs-header {
        display: flex;
        align-items: center;
        flex: 1;
        overflow-x: auto;
        overflow-y: hidden;
        scrollbar-width: none;
        -webkit-overflow-scrolling: touch;
        
        // 隐藏滚动条
        &::-webkit-scrollbar {
          display: none;
        }
        
        // 防止flex子元素收缩
        .tab-items-wrapper {
          display: flex;
          align-items: center;
          min-width: max-content;
          padding: 0 8px;
        }
        
        .tab-item {
          display: flex;
          align-items: center;
          padding: 12px 16px;
          cursor: pointer;
          border-bottom: 2px solid transparent;
          margin-right: 8px;
          position: relative;
          transition: all 0.3s ease;
          
          &:hover {
            color: #1890ff;
            background-color: #f5f5f5;
          }
          
          &.tab-active {
            color: #1890ff;
            border-bottom-color: #1890ff;
            background-color: #f5f5f5;
          }
          
          &.tab-unclosable {
            font-weight: 500;
          }
          
          .tab-title {
            margin-right: 8px;
            font-size: 14px;
            white-space: nowrap;
          }
          
          .tab-close {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            font-size: 12px;
            
            &:hover {
              background-color: rgba(0, 0, 0, 0.1);
              color: #ff4d4f;
            }
          }
        }
      }
    }
    
    // 标签页内容区域
    .tabs-content {
      flex: 1;
      overflow: auto;
      position: relative;
      background-color: #fff;
      
      .tab-pane {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        display: none;
        padding: 0;
        overflow: auto;
        
        &.tab-pane-active {
          display: block;
        }
      }
    }
  }
  
  // dialog模式样式
  .dialog-container {
    height: 100%;
    width: 100%;
  }
}
</style>